<!-- 位置选择器组件 -->
<template>
    <div class="location-picker">
        <div class="map-container" ref="mapContainer"></div>
        <div class="location-info" v-if="address">
            <el-descriptions :column="1" border>
                <el-descriptions-item label="地址">
                    {{ address.formattedAddress }}
                </el-descriptions-item>
                <el-descriptions-item label="省份">
                    {{ address.province }}
                </el-descriptions-item>
                <el-descriptions-item label="城市">
                    {{ address.city }}
                </el-descriptions-item>
                <el-descriptions-item label="区县">
                    {{ address.district }}
                </el-descriptions-item>
                <el-descriptions-item label="街道">
                    {{ address.street }}
                </el-descriptions-item>
            </el-descriptions>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { createLocationPicker } from '@/utils/amap'

const props = defineProps<{
    modelValue?: [number, number]
    height?: string
}>()

const emit = defineEmits<{
    (e: 'update:modelValue', value: [number, number]): void
    (e: 'change', value: { location: [number, number]; address: any }): void
}>()

const mapContainer = ref<HTMLElement | null>(null)
const address = ref<any>(null)
let picker: any = null

onMounted(async () => {
    if (!mapContainer.value) return

    picker = await createLocationPicker(mapContainer.value.id, {
        zoom: 13
    })

    // 如果有初始位置，设置到地图上
    if (props.modelValue) {
        await picker.setLocation(props.modelValue)
    }

    // 监听位置变化
    picker.map.on('location-change', (e: any) => {
        address.value = e.address
        emit('update:modelValue', e.location)
        emit('change', e)
    })
})

onUnmounted(() => {
    if (picker?.map) {
        picker.map.destroy()
    }
})

// 对外暴露方法
defineExpose({
    async setLocation(location: [number, number]) {
        if (picker) {
            await picker.setLocation(location)
        }
    },
    async getLocation(): Promise<[number, number]> {
        if (picker) {
            return await picker.getLocation()
        }
        return [0, 0]
    }
})
</script>

<style scoped>
.location-picker {
    width: 100%;
    display: flex;
    gap: 16px;
}

.map-container {
    flex: 1;
    height: v-bind(height || '400px');
    border-radius: 4px;
    overflow: hidden;
    border: 1px solid var(--el-border-color);
}

.location-info {
    width: 300px;
    flex-shrink: 0;
}
</style>